import Vue from 'vue';
import Vuex from 'vuex';
import _ from 'lodash';

Vue.use(Vuex);

// 初始化状态
const state = {
  tableDataList: [],
}

const mutations = {
  addOrderList(state, item) {
    const deepItem = _.cloneDeep(item);  // 这里使用深拷贝避免item的数据也变化的问题
    const { tableDataList } = state;
    const findItem = _.find(tableDataList, ele => ele.goodsId === deepItem.goodsId);
    const findIndex = _.findIndex(tableDataList, ele => ele.goodsId === deepItem.goodsId);
    if (findItem) {
      findItem.count += 1; // 这样直接会修改原来数组的元素的值，用filter也一样，这样会和forEach的效果一样
      findItem.price = deepItem.price;
      findItem.total = findItem.count * deepItem.price;
      // 直接修改属性是不会更新状态本身的，追踪不到state的变化，所以这里用了Vue.set()使其进行state状态的追踪
    } else {
      deepItem.count = 1;
      deepItem.total = +(deepItem.price);
      tableDataList.push(deepItem);
    }
  },
  deleteOrderList(state, item) {
    const deepItem = _.cloneDeep(item);  // 这里使用深拷贝避免item的数据变化的问题
    const { tableDataList } = state;
    const findItem = _.find(tableDataList, ele => ele.goodsId === deepItem.goodsId);
    const findIndex = _.findIndex(tableDataList, ele => ele.goodsId === deepItem.goodsId);
    if (deepItem.count > 1) {
      // count的数量多余1个
      findItem.count -= 1;
      findItem.total =  findItem.count * deepItem.price;
    } else {
      // count的数量只有一个
      tableDataList.splice(findIndex, 1);
    }
  },
  deleteAllOrder(state) {
    // 清除全部
    const { tableDataList } = state;
    tableDataList.splice(0, tableDataList.length);
  }
}

export default new Vuex.Store({
  state,
  mutations,
})